use rand::Rng;
use tessor::{
	geom::{Point, Polyline, Vector},
	CapKind, JoinKind, Mesh, StrokeOptions, Stroker,
};
use tessor_viewer::{draw, Draw, Viewer};

fn main() {
	let mut rng = rand::thread_rng();
	let mut positions = Vec::new();
	let mut velocities = Vec::new();
	for _ in 0..5 {
		positions.push(Point::new(2.0 * rng.gen::<f32>() - 1.0, 2.0 * rng.gen::<f32>() - 1.0));
		velocities.push(Vector::new(0.002 * rng.gen::<f32>() - 0.001, 0.002 * rng.gen::<f32>() - 0.001));
	}
	let viewer = Viewer::new();
	viewer.run(move || {
		for (position, velocity) in positions.iter_mut().zip(velocities.iter_mut()) {
			*position = Point::new(position.x() + velocity.x(), position.y() + velocity.y());
			if position.x() < -1.0 {
				*position = Point::new(-2.0 - position.x(), position.y());
				*velocity = Vector::new(-velocity.x(), velocity.y());
			}
			if 1.0 < position.x() {
				*position = Point::new(2.0 - position.x(), position.y());
				*velocity = Vector::new(-velocity.x(), velocity.y());
			}
			if position.y() < -1.0 {
				*position = Point::new(position.x(), -2.0 - position.y());
				*velocity = Vector::new(velocity.x(), -velocity.y());
			}
			if 1.0 < position.y() {
				*position = Point::new(position.x(), 2.0 - position.y());
				*velocity = Vector::new(-velocity.x(), -velocity.y());
			}
		}
		let polylines = [Polyline {
			vertices: positions.clone(),
		}];
		let mut mesh = Mesh::new();
		Stroker::new().stroke(
			&polylines,
			StrokeOptions {
				stroke_width: 0.1,
				cap_kind: CapKind::Round,
				join_kind: JoinKind::Round,
				..Default::default()
			},
			&mut mesh,
		);
		Mesh {
			vertices: vec![[-0.5, -0.5], [0.5, -0.5], [-0.5, 0.5], [0.5, 0.5]],
			indices: vec![0, 1, 2, 2, 1, 3],
		}
		.draw(draw::Options {
			triangle_color: [1.0, 0.5, 0.5, 1.0],
			edge_color: [0.0, 0.0, 0.0, 0.0],
			vertex_color: [0.0, 0.0, 0.0, 0.0],
		});
		mesh.draw(draw::Options {
			triangle_color: [0.5, 0.5, 1.0, 0.5],
			vertex_color: [0.0, 1.0, 0.5, 0.8],
			edge_color: [1.0, 0.0, 0.0, 0.8],
			..draw::Options::default()
		});
	});
}
